package com.hengpeng.msls.port;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hengpeng.itfinbase.constants.TransCodeConstants;
import com.hengpeng.itfinbase.message.partner.NotifyRequestMsg;
import com.hengpeng.itfinbase.message.partner.NotifyResponseMsg;
import com.hengpeng.msls.domain.LoginUser;
import com.hengpeng.msls.service.userInfo.UserInfoService;
import com.hengpeng.msls.util.CommUtil;

/**
 * <pre>
 * 充值
 * </pre>
 * @author shanguogang
 * @version 1.0, 2015-8-17
 */
@Controller
@RequestMapping(value = "/recharge")
public class RechargeController
{
	private Log logger = LogFactory.getLog(RechargeController.class);

	@Autowired
	@Qualifier("portFactoryImpl")
	private PortFactory portFactory;

	@Autowired
	private UserInfoService userService;

	/**
	 * 充值请求
	 * @param request
	 * @param map
	 * @param providerId 支付商ID
	 * @param payMoney 支付金额
	 * @return
	 *//*
	@RequestMapping(value = "/member_login_operate/payRequest")
	public String payRequest(HttpServletRequest request, ModelMap map, String providerId, String payMoney)
	{
		String requestHtml = "";
		if (CommUtil.isEmptys(providerId, payMoney))
		{
			requestHtml = "参数不能为空";
		}
		else
		{
			PayResponseMsg payResponse = service.doRecharge(request, providerId, payMoney);
			if (!CommUtil.isEmpty(payResponse))
			{
				if (CommUtil.isSuccess(payResponse))
				{
					requestHtml = payResponse.getOrderFormContent();
				}
				else
				{
					requestHtml = payResponse.getMessage();
				}
			}
			else
			{
				requestHtml = "请求出错，请重试！";
				logger.info("充值请求出错，返回null");
			}
		}
		map.put("requestHtml", requestHtml);
		return "/page/wap/recharge_ret.jsp";
	}*/

	/**
	 * 充值响应
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/payResponse")
	public String payResponse(HttpServletRequest request, ModelMap map)
	{
		String rechargeResult = null;
		String result = request.getParameter("result");
		if ("success".equals(result))
		{
			// 成功
			rechargeResult = "success";
			LoginUser loginUser = CommUtil.getLoinUser(request);
			if (!CommUtil.isEmpty(loginUser))
			{
				CommUtil.refreshAccount(loginUser, request, userService);
			}
		}
		else
		{
			rechargeResult = "faild";
		}
		map.put("rechargeResult", rechargeResult);
		return "/page/wap/recharge_res.jsp";
	}

	/**
	 * 支付宝安卓客户端支付网关新框架充值响应
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/payNotifyNew{providerId}")
	public void payNotifyNew(HttpServletRequest request, HttpServletResponse response, ModelMap map,
			@PathVariable String providerId)
	{
		logger.info("充值接收通知处理开始:" + providerId);
		String result = "faild";
		PrintWriter out = null;
		try
		{
			out = response.getWriter();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		if (!CommUtil.isEmpty(providerId))
		{
			String paramterStr = getParames(request);
			
			NotifyRequestMsg requestMessage = new NotifyRequestMsg();
			requestMessage.setIsBgNotify(false);
			requestMessage.setParamString(paramterStr);
			requestMessage.setProviderId(providerId);
			requestMessage.setTransType(TransCodeConstants.PartnerTransCode.NOTIFY);
			//设置访问哪个接口
			Map<String, String> parameterMap = new HashMap<String, String>();
			parameterMap.put("RespType", "NetSave");
			requestMessage.setParameter(parameterMap);
			
			NotifyResponseMsg notifyResponse =(NotifyResponseMsg)portFactory.remoteTrans(requestMessage);
			if (!CommUtil.isEmpty(notifyResponse))
			{
				if (CommUtil.isSuccess(notifyResponse))
				{
					result = "success";
				}
				else
				{
					logger.info(notifyResponse.getRespDesc());
					logger.info("notify params:" + paramterStr);
				}
			}
			else
			{
				logger.info("支付宝充值通知处理出错，BS返回null");
				logger.info("notify params:" + paramterStr);
			}
		}
		out.write(result);
		out.flush();
		out.close();
	}

	/**
	 * 充值接收通知
	 * @param providerId 支付商编号
	 * @see url样例：http://localhost:8080/recharge/payNotify1007.htm
	 */
/*	@RequestMapping(value = "/payNotify{providerId}")
	public void payNotify(HttpServletRequest request, HttpServletResponse response, @PathVariable String providerId)
	{
		logger.info("充值接收通知处理开始:" + providerId + "  返回参数列表:" + getParames(request));
		String result = "faild";
		PrintWriter out = null;
		try
		{
			out = response.getWriter();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		if (!CommUtil.isEmpty(providerId))
		{
			String paramterStr = getParames(request);
			PayNotifyResponseMsg notifyResponse = service.doRechargeRes(paramterStr, providerId);
			if (!CommUtil.isEmpty(notifyResponse))
			{
				if (CommUtil.isSuccess(notifyResponse))
				{
					result = "success";
				}
				else
				{
					logger.info(notifyResponse.getMessage());
					logger.info("notify params:" + paramterStr);
				}
			}
			else
			{
				logger.info("支付宝充值通知处理出错，BS返回null");
				logger.info("notify params:" + paramterStr);
			}
		}
		out.write(result);
		out.flush();
		out.close();
	}*/

	/**
	 * 充值通知封装参数
	 * @param request
	 * @return key1=value1&key2=value2
	 */
	@SuppressWarnings("unchecked")
	private String getParames(HttpServletRequest request)
	{
		StringBuffer parameter = new StringBuffer();
		Enumeration<String> params = request.getParameterNames();
		while (params.hasMoreElements())
		{
			String paramName = params.nextElement();
			parameter.append("&" + paramName.toLowerCase() + "=" + request.getParameter(paramName));
		}
		if (parameter.length() > 0)
		{
			parameter.delete(0, 1);
		}
		return parameter.toString();
	}
}
